package com.company.cloud.common.ribbon.config;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.company.cloud.common.constant.CommonConstant;

import feign.RequestInterceptor;

/**
 * feign拦截器，只包含http相关数据
 */
public class FeignHttpInterceptorConfig {

	protected List<String> requestHeaders = new ArrayList<String>();

	@PostConstruct
	public void initialize() {
//		requestHeaders.add(SecurityConstants.USER_ID_HEADER);
//		requestHeaders.add(SecurityConstants.ROLE_HEADER);
		requestHeaders.add(CommonConstant.USER_HEADER);
		requestHeaders.add(CommonConstant.VERSION_HEADER);
	}

	@Bean
	public RequestInterceptor httpFeignInterceptor() {
		return template -> {
			System.out.println("+++++++++++++++++++ FeignHttpInterceptorConfig:httpFeignInterceptor");
			ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
					.getRequestAttributes();
			if (attributes != null) {
				HttpServletRequest request = attributes.getRequest();
				Enumeration<String> headerNames = request.getHeaderNames();
				if (headerNames != null) {
					String headerName;
					String headerValue;
					while (headerNames.hasMoreElements()) {
						headerName = headerNames.nextElement();
						if (requestHeaders.contains(headerName)) {
							headerValue = request.getHeader(headerName);
							template.header(headerName, headerValue);
						}
					}
				}
			}
		};

	}

}
